import Vue from 'vue'
import VueRouter from 'vue-router'
// 按需引入token.js中的getToken方法
import { getToken } from '../utils/token'
Vue.use(VueRouter)

// 导入页面
import Login from '../views/login/Login'
import Layout from '../views/layout/Index'
import Welcome from '../views/layout/welcome/Index'
import Chart from '../views/layout/chart/Index'
import User from '../views/layout/user/Index'
import Question from '../views/layout/question/Index'
import Enterprice from '../views/layout/enterprise/Index'
import Subject from '../views/layout/subject/Index'
import NotFound from '../views/404/NotFound'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/layout',
    component: Layout,
    children: [
      {
        path: 'welcome',
        component: Welcome
      },
      {
        path: '',
        redirect: 'welcome'
      },
      {
        path: 'chart',
        component: Chart
      },
      {
        path: 'user',
        component: User
      },
      {
        path: 'question',
        component: Question
      },
      {
        path: 'enterprise',
        component: Enterprice
      },
      {
        path: 'subject',
        component: Subject
      },
      {
        path: '*',
        component: NotFound
      }
    ]
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login'] //白名单
/* beforeEach 导航守卫
   to 去往何处 from 从何而来 next 控制去不去或者去到哪里 并且必须要调用 否则会一直卡在这
   next() 不加参数--正常跳转到下一个页面, 加参数--跳转到指定页面
*/
router.beforeEach((to, from, next) => {
  // 访问的路径在白名单中
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
